package dao.mysql;

import dao.DAOException;
import java.sql.*;

/**
 *
 * @author salvador
 */
public class MySqlDBConnection {

    private static MySqlDBConnection DBConnection;
    private static Connection myConnection;

    public MySqlDBConnection() throws DAOException
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            try
            {
                String URI = dao.DBConnection.getURI();
                String user = dao.DBConnection.getUser();
                String password = dao.DBConnection.getPassword();
            	
            	myConnection = DriverManager.getConnection("jdbc:mysql://" + URI, user, password);
            }
            catch (SQLException ex)
            {
                throw new DAOException(ex.getErrorCode(), ex.getMessage());
            }
        }
        catch (ClassNotFoundException ex)
        {
            throw new DAOException(300, ex.getMessage());
        }

    }

    public static MySqlDBConnection getInstance() throws DAOException
    {
        if(DBConnection == null)
            DBConnection = new MySqlDBConnection();
        return DBConnection;
    }
    
    public static MySqlDBConnection Test() throws DAOException
    {
    	return new MySqlDBConnection();
    }

    public ResultSet executeQuery(String query) throws DAOException
    {
        ResultSet rs = null;
        try
        {
            Statement st = myConnection.createStatement();
            rs = st.executeQuery(query);
        }
        catch (SQLException ex)
        {
            throw new DAOException(ex.getErrorCode(), ex.getMessage());
        }
        
        return rs;
    }

    public int executeUpdate(String query) throws DAOException
    {
        int rowCount = 0;
        try
        {
            Statement st = myConnection.createStatement();
            rowCount = st.executeUpdate(query);
        }
        catch (SQLException ex)
        {
            throw new DAOException(ex.getErrorCode(), ex.getMessage());
        }
        return rowCount;
    }

    public void close() throws DAOException
    {
        try
        {
            myConnection.close();
        }
        catch (SQLException ex)
        {
            throw new DAOException(ex.getErrorCode(), ex.getMessage());
        }
    }

}
